﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using KPIS.GERP.Models.Class;
using KPIS.GERP.Models.ICM;
using KPIS.GERP.Models.SYS;
using KPIS.GERP.Models.ViewModel;
using System.Data;
using System.ComponentModel;

namespace KPIS.GERP.WEB.GIMS.Class
{
    public static class GimsUtilities
    {
        public static VMInitialStartLog InitialStartLog { get; set; }
        public static string Message { get; set; }
        public static DateTime? LastMessageDateTime { get; set; } 
        
        static GimsUtilities()
        {
            InitialStartLog = new VMInitialStartLog();
        }
        
        public static bool ContentOnly
        {
            get { return HttpContext.Current.Session["ContentOnly"] as bool? ?? false; }
            set { HttpContext.Current.Session["ContentOnly"] = value; }
        }

        public static VMInitialStartLog GetInitialTime()
        {
            return InitialStartLog;
        } 

        public static void DevMessageTestAdd(string str)
        {
            var now = DateTime.Now;
            var priv = LastMessageDateTime ?? now;
            LastMessageDateTime = now;
            var diff = now.Subtract(priv);

            Message += (!str.StartsWith("#") ? "&hearts;" : "") + str + (!str.StartsWith("#") ? " (Delay " + Models.Class.StringFormat.TimeSpan(diff) + ")" : "") + "<br/>\r\n";
        }

        public static string DevMessageTestToString
        {
            get { return Message; }
        }

        public static string ControllerName(HtmlHelper context)
        {
            return (string) context.ViewContext.RouteData.GetRequiredString("controller");
        }

        public static string ActionName(HtmlHelper context)
        {
            return (string) context.ViewContext.RouteData.GetRequiredString("action");
        }

        public static string ControllerName(ControllerContext context)
        {
            return (string) context.RouteData.Values["Controller"];
        }

        public static string ActionName(ControllerContext context)
        {
            return (string) context.RouteData.Values["Action"] as string;
        }

        public static string ClientIp
        {
            get { return HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"]; }
        }

        public static string ThisSystemId
        {
            get { return "WEBGIMS"; }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="strLayoutName">"Site", "Empty"</param>
        /// <returns></returns>
        public static string GetLayout(string strLayoutName)
        {
            string strResult = "";
            switch (strLayoutName.ToLower().Trim())
            {
                case "site":
                    strResult = "~/Views/Shared/_SiteLayout.cshtml";
                    break;
                case "empty":
                    strResult = "~/Views/Shared/_EmptyLayout.cshtml";
                    break;
                default:
                    break;
            }
            return strResult;
        }

        public static bool IsSameAction(ControllerContext context, string url)
        {
            url = MapTodefaultRoute(context, url);

            return CompareUtility.IsStringsEqual(ActionName(context), GetActionName(context, url));
        }

        public static bool IsSameController(ControllerContext context, string url)
        {
            url = MapTodefaultRoute(context, url);

            return CompareUtility.IsStringsEqual(ControllerName(context), GetControllerName(context, url));
        }

        public static string GetControllerName(ControllerContext context, string url)
        {
            url = MapTodefaultRoute(context, url);
            string controllerName = url.Split('/')[1];
            return controllerName;
        }

        public static string GetActionName(ControllerContext context, string url)
        {
            url = MapTodefaultRoute(context, url);
            string actionName = url.Split('/')[2];
            return actionName;
        }

        public static RouteValueDictionary GetDefaultRouteObject(ControllerContext context)
        {
            var result = new RouteValueDictionary();
            result.Add("Controller", context.RouteData.Values["Controller"]);
            result.Add("Action", context.RouteData.Values["Action"]);
            return result;
        }

        public static string DefaultUrl(ControllerContext context)
        {
            var defaultRoute = GetDefaultRouteObject(context);
            return "/" + defaultRoute["controller"] + "/" + defaultRoute["action"];
        }

        public static string MapTodefaultRoute(ControllerContext context, string url)
        {
            var currentUrl = url;
            var currentUrlSubStr = currentUrl.Split('/');
            var controllerName = currentUrlSubStr.ElementAtOrDefault(1);
            var actionName = currentUrlSubStr.ElementAtOrDefault(2);


            var defaultRoute = GetDefaultRouteObject(context);
            url = "/" + (String.IsNullOrEmpty(controllerName) ? defaultRoute["controller"] : controllerName) +
                  "/" + (String.IsNullOrEmpty(actionName) ? defaultRoute["action"] : actionName);

            return url;
        }

        public static bool IsSameControllerAndAction(string controller1, string controller2, string action1, string action2)
        {
            return Models.Class.CompareUtility.IsObjectToStringEqual(controller1, controller2) &&
                   Models.Class.CompareUtility.IsObjectToStringEqual(action1, action2);
        }

        public static string GetPurchaseRequestStatus(int PrId)
        {
            string strResult = "";
            var servicePr = new PurchaseRequestService.PurchaseRequestServiceClient();
            var serviceBid = new BidService.BidServiceClient();
            var modelPr = servicePr.Select(new PurchaseRequest() { PrId = PrId }, new[] { "MasPurchaseMethod" }).FirstOrDefault();
            var modelBid = serviceBid.SelectBid(new Bid() { PrId = PrId, RecordStatus = "!" + RecordStatus.DeletedStatus }, null).FirstOrDefault();

            if (modelBid != null)
            {
                bool Selected = false;
                var modelBidders = serviceBid.SelectBidder(new Bidder {BidId = modelBid.BidId}, null);

                foreach (Bidder modelBidder in modelBidders)
                {
                    if (modelBidder.WinnerStatus == "1")
                    {
                        Selected = true;
                    }
                }

                if (Selected)
                {
                    strResult = "คัดเลือกเสร็จแล้ว";
                }
                else if (modelBidders.Length > 0)
                {
                    strResult = "อยู่ขั้นตอนคัดเลือกผู้เสนอราคา";
                }
                else
                {
                    strResult = "อยู่ขั้นตอนประกาศ : " + RecordStatus.RecordStatusName(modelBid.RecordStatus);
                }

                //var modelBid = serviceBid.SelectBid(new Bid() { PrId = m.PrId, RecordStatus = "!" + RecordStatus.DeletedStatus }, null).FirstOrDefault();
            }
            else if (modelPr != null && modelPr.MasPurchaseMethod != null && (modelPr.MasPurchaseMethod.IsBid.HasValue && modelPr.MasPurchaseMethod.IsBid.Value))
            {
                strResult = "อยู่ขั้นตอนขอซื้อ-ขอจ้าง : " + RecordStatus.RecordStatusName(modelPr.RecordStatus);
            }
            else if (modelPr != null)
            {
                strResult = RecordStatus.RecordStatusName(modelPr.RecordStatus);
            }

            return strResult;
        }

        public static string Base64Decode(string data)
        {
            try
            {
                System.Text.UTF8Encoding encoder = new System.Text.UTF8Encoding();
                System.Text.Decoder utf8Decode = encoder.GetDecoder();

                byte[] todecode_byte = Convert.FromBase64String(data);
                int charCount = utf8Decode.GetCharCount(todecode_byte, 0, todecode_byte.Length);
                char[] decoded_char = new char[charCount];
                utf8Decode.GetChars(todecode_byte, 0, todecode_byte.Length, decoded_char, 0);
                string result = new String(decoded_char);
                return result;
            }
            catch (Exception e)
            {
                throw new Exception("Error in base64Decode" + e.Message);
            }
        }
        public static DataTable ToDataTable<T>(this IList<T> data, params int[] cols)
        {
            PropertyDescriptorCollection props =
                TypeDescriptor.GetProperties(typeof(T));
            DataTable table = new DataTable();
            for (int i = 0; i < props.Count; i++)
            {
                PropertyDescriptor prop = props[i];
                table.Columns.Add(prop.Name);
            }
            object[] values = new object[props.Count];
            foreach (T item in data)
            {
                if (cols != null && cols.Any())
                { 
                    for (int i = 0; i < cols.Length; i++)
                    {
                        values[i] = props[cols[i]].GetValue(item);
                    }
                }
                else
                {
                    for (int i = 0; i < values.Length; i++)
                    {
                        values[i] = props[i].GetValue(item);
                    }
                }
                table.Rows.Add(values);
            }
            return table;
        }

        public static string SsMngToString()
        {
            StringBuilder result = new StringBuilder();
            result.Append("This is session<br>");
            foreach (var s in HttpContext.Current.Session.Keys)
            {
                result.Append(s);
                result.Append("=");
                result.Append(HttpContext.Current.Session[s.ToString()]);
                result.Append("<br>");
            }
            result.Append("<br>");
            result.Append("This is cookie<br>");
            HttpCookie ck = HttpContext.Current.Request.Cookies["UserDetail"];
            if (ck != null && ck.HasKeys)
            {
                foreach (var s in ck.Values)
                {
                    if (s != null)
                    {
                        result.Append(s);
                        result.Append("=");
                        result.Append(ck[s.ToString()]);
                        result.Append("<br>");
                    }
                }
            }
            return result.ToString();
        } 
    }
}